package com.alex.common.filter;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.alex.common.ILogger;

/**
 * <pre>
 * 
 * 	<filter>
 * 		<filter-name>EnvironmentFilter</filter-name>
 * 		<filter-class>
 * 			com.alex.common.filter.EnvironmentFilter
 * 		</filter-class>
 * 		<init-param>
 * 			<param-name>domainName</param-name>
 * 			<param-value>
 * 				huobi3jia.com,beijingmaiche.com,renrenweiwo.com
 * 			</param-value>
 * 		</init-param>
 * 	</filter>
 * 
 * 	<filter-mapping>
 * 		<filter-name>EnvironmentFilter</filter-name>
 * 		<url-pattern>/*</url-pattern>
 * 	</filter-mapping>
 * 
 * </pre>
 * 
 * @author Alex hu
 * 
 */
public class EnvironmentFilter implements Filter {

	public static final String REQ_HOST_NAME = "hostname";

	public static final String APP_HOST_INFO = "hostinfo";

	public static boolean isTest = true;

	public static ServletContext application;

	public static String[] domainNames;

	public static String webContext;

	@Override
	public void destroy() {
		return;
	}

	@Deprecated
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;

		String host = "";// HostUtils.getRequestHost(request);
		// kill web context
		String uri = request.getRequestURI().replaceFirst(webContext, "");
		String qstr = request.getQueryString();
		request.setAttribute(REQ_HOST_NAME, host);

		// not filter static file
		if (request.getRequestURI().indexOf("/s/") == -1) {
			// access recorder
			// String remoteHostInfo = new StringBuilder("Addr=")
			// .append(HostUtils.getRemoteAddr(request)).append(", Host=")
			// .append(host).append(", URI=").append(uri)
			// .append(", QStr: ").append(qstr).toString();
			// ILogger.logger_access.info(remoteHostInfo);

			// domain reDispatcher
			for (int i = 1; i < domainNames.length; i++) {
				if (host.indexOf(domainNames[i]) != -1) {
					String q = (qstr == null) ? "" : ("?" + qstr);
					String dispatchURI = new StringBuilder("/")
							.append(domainNames[i].replaceFirst("[.]", ""))
							.append(uri).append(q).toString();
					// ILogger.logger_access.info("  Dispatch to: " +
					// dispatchURI);
					request.getRequestDispatcher(dispatchURI).forward(req, res);
					return;
				}
			}
		}

		chain.doFilter(req, res);
	}

	public boolean testDomain(HttpServletRequest request, String domain) {
		StringBuffer url = request.getRequestURL();
		int start = url.indexOf(domain);
		if (start != -1)
			return true;
		return false;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		if (config.getServletContext().getRealPath(".")
				.indexOf("src\\main\\webapp") != -1) {
			isTest = true;
		} else {
			isTest = false;
		}
		domainNames = config.getInitParameter("domainName").trim().split(",");
		application = config.getServletContext();
		application.setAttribute("domainNames", domainNames);

		// set host infomation
		InetAddress host;
		try {
			host = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			ILogger.logger_common.error(e.getMessage(), e);
			throw new ServletException(e.getMessage(), e);
		}
		String hostinfo = host.getHostName() + " - " + host.getHostAddress();
		application.setAttribute(APP_HOST_INFO, hostinfo);

		// e.g. "/www"
		webContext = config.getServletContext().getContextPath();
		return;
	}
}
